<template>
    <view>
        <!-- #ifdef MP-WEIXIN-->
        <button type='primary' open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="wxGetUserInfo">微信登录</button>
        <!-- #endif-->
        <!-- #ifdef APP-PLUS -->
        <button type="primary" @click="getWxApp">APP中微信登录</button>
        <!-- #endif -->
    </view>
</template>

<script>
    import API from '@/utils/api.js'
    export default {
        data() {
            return {}
        },
        components: {},
        onLoad(option) {},
        methods: {
            // 微信小程序
            wxGetUserInfo(userInfo) {
                if (!userInfo.detail.iv) {
                    uni.showToast({
                        title: "您取消了授权,登录失败",
                        icon: "none"
                    });
                    return false;
                }
                // 1. 点击微信 登录 ：获取用户的信息
                console.log('userInfo', userInfo)
                //2.获取openid 唯一性
                uni.login({
                    success: function(el) {
                        console.log(el, 'sss')
                        let params = {
                            code: el.code
                        };
                        //获取openid sessinkey
                        API.getOpenId(params).then(res => {
                            if (res.success === true) {
                                uni.setStorageSync('openid', res.data.openid);
                                uni.setStorageSync('sessinkey', res.data.session_key);
                            }
                        })

                    },
                })
            },
            //微信 小程序   登录 App
            getWxApp: function() {
                //1.获取服务商https://uniapp.dcloud.io/api/plugins/provider?id=getprovider
                uni.getProvider({
                    service: 'oauth',
                    success: function(res) {
                        console.log(res.provider)
                        // 是否有微信
                        if (~res.provider.indexOf('weixin')) {
                            uni.login({
                                provider: 'weixin',
                                success: function(loginRes) {
                                    // 获取微信登录的信息
                                    console.log(JSON.stringify(loginRes));
                                    // 获取用户信息
                                    uni.getUserInfo({
                                        provider: 'weixin',
                                        success: function(infoRes) {
                                            console.log('用户昵称为：' + infoRes.userInfo
                                                .nickName);
                                        }
                                    });
                                }
                            });
                        }
                    }
                });
            }

        },
    }
</script>

<style>
</style>
